package com.neihe.listenner;

import com.neihe.common.constant.Const;
import com.neihe.listenner.event.SendCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 发送邮箱验证码监听器
 */
@Slf4j
@Component
public class SendEmailEventListener implements ApplicationContextAware {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String username;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 监听发送邮箱验证码事件执行器
     *
     * @param event 事件
     */
    @EventListener(classes = SendCode.class)
    @Async(value = "mailAsyncThread")
    public void sendEmailCode(SendCode event) {

        String threadName = Thread.currentThread().getName();
        long threadId = Thread.currentThread().getId();
        log.info("线程 [{}:{}] 开始处理发送邮箱验证码事件", threadName, threadId);

        String email = event.getEmail();
        String code = event.getCode();
        SimpleMailMessage mailMessage = createMessage(
                "OneFile - 邮箱登录验证码",
                "尊敬的用户：您好！ \n" +
                        "您正在进行注册/登录/重置密码操作，请输入以下验证码完成操作：\n" + code
                        + "\n有效时间5分钟，为了保障您的账户安全，请勿向他人泄露验证码信息。", email
        );
        mailSender.send(mailMessage);
        redisTemplate.opsForValue().set(Const.VERIFY_EMAIL_CODE + email, code, 5, TimeUnit.MINUTES);
    }

    /**
     * 快速封装简单邮件消息实体
     *
     * @param title   标题
     * @param content 内容
     * @param email   收件人
     * @return 邮件实体
     */
    private SimpleMailMessage createMessage(String title, String content, String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(title);
        message.setText(content);
        message.setTo(email);
        message.setFrom(username);
        return message;
    }
}
